package com.uziot.bucket.service;

import com.uziot.bucket.dao.mapper.PersionHouseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能描述: <br>
 * <>
 *
 * @author shidt
 * @date 2022-06-01 21:12
 */

@Service
public class PersonHouseService {
    private static final Logger log = LoggerFactory.getLogger(PersonHouseService.class);

    @Autowired
    private PersionHouseMapper persionHouseMapper;

    private static final Integer ROW_NUM = 50000;

    public void createFile() {
        try {
            String fileName = "PERSON_HOUSE" + System.currentTimeMillis() + ".txt";
            // 总数
            Integer count = persionHouseMapper.selectCount();
            // 分批写文件
            splitWriteFile(ROW_NUM, count, fileName, "E:\\");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param rowNum   一页行数
     * @param count    查询总数
     * @param fileName 文件名
     * @param path     路径
     */
    public void splitWriteFile(int rowNum, int count, String fileName, String path) throws Exception {

        // 设置一个基准条数，和起始位置
        int startIndex = 0;
        // 当前页
        int currentPage = 0;
        // 页数
        int pages = count / rowNum;
        if (count % rowNum != 0) {
            pages += 1;
        }

        log.info("当前抽取数据总页数：" + pages);

        List<Map<String, Object>> list;
        int result = 1;
        // 用一个循环去查询，循环一次增加一个基准条数
        // 查询的退出条件为：遍历完所有页数
        while (currentPage < pages) {
            // 循环抽取
            list = persionHouseMapper.selectList(startIndex, rowNum);

            currentPage++;
            startIndex += rowNum;
            // 在循环中将文件写出
            result = writeCollateFile(list, fileName, path);
            // 返回行数是 -1 时，说明文件没有正确写入
            if (-1 == result) {
                throw new Exception("文件写入失败");
            }
            list.clear();
        }
        // 为了实现查询无结果时，写一个空文件
        if (pages == 0) {
            result = writeCollateFile(null, fileName, path);
            // 返回行数是 -1 时，说明文件没有正确写入
            if (-1 == result) {
                throw new Exception("文件写入失败");
            }
        }
    }

    /**
     * 写文件
     */
    private int writeCollateFile(List<Map<String, Object>> list, String fileName, String path) {
        //用来记录行数
        int lineNumber = 0;
        StringBuilder builder = new StringBuilder();

        if (null != list && !list.isEmpty()) {
            for (Map<String, Object> map : list) {
                String addContent = addContent(map);
                builder.append(addContent);
                lineNumber++;
            }
        }
        String contentAll = builder.toString();
        boolean fileResult = FileHandleUtils.writeFile(contentAll, fileName, path, true);
        if (fileResult) {
            if (log.isDebugEnabled()) {
                log.debug(path + fileName + "文件生成");
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(path + fileName + "文件生成失败");
            }
            lineNumber = -1;
        }
        return lineNumber;
    }

    /**
     * 组织文件内容
     */
    private String addContent(Map<String, Object> map) {
        return map.get("NAME") +
                "-" +
                map.get("CTFID") +
                "\n";
    }

}
